﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;

namespace wpfVideoThumbnail
{
	/// <summary>
	/// Interaction logic for Window1.xaml
	/// </summary>
	public partial class Window1 : Window
	{
		public Window1()
		{
			InitializeComponent();
		}
		private delegate void setImageDelegate(string controlName, BitmapFrame frame);
		private void setImage(string controlName, BitmapFrame frame)
		{
			var control = FindName(controlName);
			if (control != null)
				((Image)control).Source = frame;
		}

		private void makeThumbnails(BitmapFrame frame, object state)
		{
			Dispatcher.Invoke(new setImageDelegate(setImage), (string)state, frame);
		}

		private void makeJpeg(BitmapFrame frame, object state)
		{
			var encoder = new JpegBitmapEncoder();
			encoder.Frames.Add(frame);

			string filename = (string)state + ".jpg";
			using (var fs = new FileStream(filename, FileMode.Create))
				encoder.Save(fs);
		}

		private void Button_Click(object sender, RoutedEventArgs e)
		{
			var source = video.Source;

			VideoScreenShot.CaptureScreenAsync(source, new Dictionary<TimeSpan, object> { 
				{TimeSpan.FromSeconds(10), "image0"} ,
				{TimeSpan.FromSeconds(20), "image1"} ,
				{TimeSpan.FromSeconds(30), "image2"} ,
				{TimeSpan.FromSeconds(40), "image3"} ,
			}, .1, makeJpeg, makeThumbnails);
			//VideoScreenShot.CaptureScreenAsync(source, TimeSpan.FromSeconds(10), "image0", .1, makeJpeg, makeThumbnails);
			//VideoScreenShot.CaptureScreenAsync(source, TimeSpan.FromSeconds(43) + TimeSpan.FromMilliseconds(760), "image1", makeThumbnails);
		}
	}
}
